﻿using Cinch;
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace FR.SAFTAnalyserLite.Views
{
    /// <summary>
    /// Interaction logic for SaftView.xaml
    /// </summary>
    public partial class SaftView : UserControl
    {
        public SaftView()
        {
            InitializeComponent();
        }

        private void SaftFile_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                if (ValidateFileDrop(files, ".xml"))
                    Mediator.Instance.NotifyColleaguesAsync<string>(MessageType.OPEN_SAFT_FILE, files[0]);
            }
        }

        private void PublicKeyFile_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                if (ValidateFileDrop(files, ".txt", ".pem"))
                    (this.DataContext as SAFTAnalyserLite.ViewModels.SaftViewModel).PublicKeyFileName = files[0];
            }
        }

        private void PrivateKeyFile_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

                if (ValidateFileDrop(files, ".txt", ".pem"))
                    (this.DataContext as SAFTAnalyserLite.ViewModels.SaftViewModel).PrivateKeyFileName = files[0];
            }
        }

        private bool ValidateFileDrop(string[] filenames, params string[] fileFormats)
        {
            if (filenames == null || filenames.Length == 0)
                return false;

            string filename = filenames[0];

            if (File.Exists(filename) == false)
                return false;

            FileInfo info = new FileInfo(filename);
            foreach (string fileFormat in fileFormats)
            {
                if (info.Extension.Equals(fileFormat, StringComparison.OrdinalIgnoreCase) == true)
                    return true;
            }

            return false;
        }
    }
}
